#include "Global.h"
#include "Response.h"
#include "Request.h"
#include <cstddef>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include <sstream>
#include "TimeFunc.h"

Cache cache;

#define BUFSIZE 8192
using namespace std;

Response::Response()
{
    this->responseLength = 0;
}
Response::Response(const Response& data)
{
    this->fileName = data.fileName;
    this->method = data.method;
    this->reasonPhrase = data.reasonPhrase;
    this->responseHeaderLength = data.responseHeaderLength;
    this->responseLength = data.responseLength;
    this->statusCode = data.statusCode;
    
}
void Response::MakeHeader()
{
    this->responseHeader << "HTTP/1.1" << " " << this->statusCode << " " << this->reasonPhrase << "\r\n";
    // Headers.
    this->responseHeader << "Date: " << DateTimeNow() << "\r\n" << this->headers.str() << "\r\n";
    
    // Update responseLength.
   // resp.responseHeader.seekg(0, ios::end);
    this->responseHeaderLength = this->responseHeader.str().length();
}
void Response::SendResponse(Response& resp, int socket, string baseDir)
{
    
    char buffer[BUFSIZE];
    bzero(buffer,BUFSIZE);
    //first, write the header
    int headerLeft = resp.responseHeaderLength;
    while(headerLeft > 0)
    {
        cout << resp.responseHeader.str() << endl;
        if(headerLeft < BUFSIZE)
        {
            resp.responseHeader.read(buffer,headerLeft);
            write(socket,buffer,headerLeft);
            headerLeft = 0;
        }
        else
        {
            resp.responseHeader.read(buffer,BUFSIZE);
            write(socket,buffer,BUFSIZE);
            headerLeft -= BUFSIZE;
        }
    }
    //then, write the message body if this is a GET Method
    if(resp.method == "GET")
    {
        char buf[1024];
        getcwd(buf,1024);
        string cwd = string(buf);
        long long fileLeft = resp.responseLength;
        cout << cwd << baseDir << resp.fileName << endl;
        struct CacheItem var =  cache.FetchFromCache(cwd + baseDir + resp.fileName);
        long long counter = 0;
        
        while(var.filesize - counter > BUFSIZE)
        {
            write(socket, var.data + counter, BUFSIZE);
            counter = counter + BUFSIZE;
        }
        
        write(socket,var.data + counter, var.filesize - counter);
        
       // file.close();
    }
}
